﻿/**
 * ...
 * @author sminutoli
*/


import com.dmotiko.prune.*
import com.dmotiko.general.*
import mx.transitions.easing.Regular;
import mx.transitions.Tween;
import mx.utils.Delegate;


class ContactoSection extends Section
{
	
	private var sun_listener:Function;
	private var mcContactoBar:ContactoBar;
	
	private var txtName:TextField;
	private var txtLastName:TextField;
	private var txtAddress:TextField;
	private var txtState:TextField;
	private var txtCountry:TextField;
	private var txtEmail:TextField;
	private var txtPhone:TextField;
	private var txtMessage:TextField;
	private var mcSend:ButtonClip;
	private var mcNameError:MovieClip;
	private var mcLastNameError:MovieClip;
	private var mcEmailError:MovieClip;
	private var mcMessageError:MovieClip;
	private var mcHotLinks:MovieClip;
	private var mcSendOK:MovieClip;
	private var mcSendERROR:MovieClip;
	private var hotLinkShowFrame:Function; //ver en index.fla el simbolo "contactoHotLinks" frame 1 para encontrar la funcion showFrame();
	private var oVars:LoadVars;
	
	private var mcTimer:MovieClip;
	
	private function initClip():Void {
		super.initClip();
		
		//instancio la ContactoBar y le adjudico x e y
		mcContactoBar = ContactoBar( this.attachMovie("ContactoBar", "mcContactoBar", this.getNextHighestDepth(), { _x: 20, _y: 50 } ) );
		//me suscribo al evento Changed para poder actualizar el valor
		mcContactoBar.addEventListener( BaseClipEvent.CHANGED, Delegate.create(this, bar_changed) );
		
		//inicializo el Y del boton de enviar y de los mensajes para despues usarlos en los tweens
		mcSend["initY"] = mcSend._y; //tengo que hacer esto con el mcSend porque lo declaré como ButtonClip
		mcSendERROR.initY = mcSendERROR._y;
		mcSendOK.initY = mcSendOK._y;
		
		//le piso el evento al ButtonClip para que haga lo que quiero en el onRelease
		var root:ContactoSection = this;
		mcSend.onRelease = function() {
			root.send_form();
		}
		
		mcTimer = com.dmotiko.lib.TimerMovie.createTimer( this );
				
		sun_listener = Delegate.create(this, sun_hidden);	
		Site.getApp().addEventListener( WebSite.SECTION_CHANGED, Delegate.create( this, section_changed ) );
	}
	
	private function clearErrors():Void
	{
		mcNameError._alpha = mcLastNameError._alpha = mcEmailError._alpha = mcMessageError._alpha = 0;
	}
	
	private function send_form():Void 
	{
		oVars = new LoadVars();
		oVars.name = txtName.text;
		oVars.lastName = txtLastName.text;
		oVars.address = txtAddress.text;
		oVars.state = txtState.text;
		oVars.country = txtCountry.text;
		oVars.email = txtEmail.text;
		oVars.phone = txtPhone.text;
		oVars.message = txtMessage.text;
		oVars.mailTo = mcHotLinks.value;
		
		var aErrors:Array = new Array();
		
		if ( !FormFieldValidator.inRange(oVars.name, 3) ) { aErrors.push( mcNameError ); }
		if ( !FormFieldValidator.inRange(oVars.lastName, 3) ) { aErrors.push( mcLastNameError ); }
		if ( !FormFieldValidator.inRange(oVars.email, 5) || !FormFieldValidator.mail(oVars.email) ) { aErrors.push( mcEmailError ); }
		if ( !FormFieldValidator.inRange(oVars.message, 10, 300) ) { aErrors.push( mcMessageError ); }
				
		if ( aErrors.length > 0 ) {
			for (var i:Number = 0; i < aErrors.length; i++) 
			{
				new Tween( aErrors[i], "_alpha", Regular.easeOut, 100, 0, 2, true);
			}
		} else {
									
			oVars.sendAndLoad("http://www.prune.com.ar/sendmail.php", oVars, "POST");
			var root:ContactoSection = this;
			oVars.onLoad = function(success:Boolean):Void {
				
				if ( success && this.response == "OK" ) {
					root.mcTimer.startTimer( { delay: 1000, bind: root, listener: root.showSendOK } );
					
				} else {
					root.mcTimer.startTimer( { delay: 1000, bind: root, listener: root.showSendERROR } );
										
				}
				root.clearFields();
				root.clearErrors();
				new Tween( root.mcSend, "_y", Regular.easeOut, root.mcSend._y, root.mcSend["initY"] + 30, 0.5, true );
			}
		}
	}
	
	private function showSendOK():Void
	{
		registerTween( "showSendOK", new Tween( mcSendOK, "_y", Regular.easeOut, mcSendOK._y, mcSendOK.initY - 25, 0.5, true), false, true );	
	}
	private function showSendERROR():Void
	{
		registerTween( "showSendERROR", new Tween( mcSendERROR, "_y", Regular.easeOut, mcSendERROR._y, mcSendERROR.initY - 25, 0.5, true), false, true );	
	}
	private function showSend():Void {
		if( mcSendOK._y < mcSendOK.initY ){
			registerTween( "hideSendOK", new Tween( mcSendOK, "_y", Regular.easeOut, mcSendOK._y, mcSendOK.initY, 0.5, true));
		}
		if( mcSendERROR._y < mcSendERROR.initY ){
			registerTween( "hideSendERROR", new Tween( mcSendERROR, "_y", Regular.easeOut, mcSendERROR._y, mcSendERROR.initY, 0.5, true));
		}
		registerTween( "showSend", new Tween( mcSend, "_y", Regular.easeOut, mcSend._y, mcSend["initY"], 0.5, true));
	}
	
	private function tweenFinished( key:String, tween:Tween ):Void {
		switch( key ) {
			case "showSendOK":
			mcTimer.startTimer( { delay: 3000, bind: this, listener: showSend } );
			break;
			
			case "showSendERROR":
 			mcTimer.startTimer( { delay: 3000, bind: this, listener: showSend } );
			break;
		}
	}
	
	private function initFields():Void
	{
		txtName.restrict = txtLastName.restrict = "^0-9%&$#¿?¡!|_-*+{}";
		txtName.maxChars = txtLastName.maxChars = 30;
		txtEmail.restrict = "^áéíóúÁÉÍÓÚñÑ $%&/()\"!¡¿?çÇ";
	}
	
	private function clearFields():Void
	{
		txtName.text = txtLastName.text = txtAddress.text = txtState.text = txtCountry.text = txtEmail.text = txtPhone.text = txtMessage.text = "";
	}
	
	private function bar_changed(e):Void 
	{
		switch( e.value ) {
			case SiteSections.CONTACT:
			case SiteSections.CONTACT_ATEN:
			hotLinkShowFrame(1);
			break;
			
			case SiteSections.CONTACT_RRHH:
			//hotLinkShowFrame(2);
			Site.getApp().setSection(SiteSections.BELONG);
			break;
			
			case SiteSections.CONTACT_FRAN:
			hotLinkShowFrame(3);
			break;
			
			case SiteSections.CONTACT_IMG:
			hotLinkShowFrame(4);
			break;
		}
		mcHotLinks.value = e.value;
				
	}
	
	public function childLoaded(e):Void {
		//tuve que hacer esto porque por algún motivo extraño no me tomaba el gotoAndStop
		//ver en index.fla el simbolo "contactoHotLinks" frame 1 para encontrar la funcion showFrame();
		if ( e == mcHotLinks ) hotLinkShowFrame = e.showFrame;
	}
	
	private function section_changed(e):Void 
	{
		//hago indexOf porque me fijo que pertenezca básicamente al grupo de contacto
		if ( e.section.indexOf( SiteSections.CONTACT ) >= 0 ) {
			Site.getApp().getClips().getSol().addEventListener( BaseClipEvent.CHANGED, sun_listener );			
			
		} else {
			hide();
		}
	}
	
	private function sun_hidden():Void 
	{
		//hago indexOf porque me fijo que pertenezca básicamente al grupo de contacto
		if ( Site.getApp().getSection().indexOf( SiteSections.CONTACT ) < 0 ) return;
		Site.getApp().getClips().getSol().removeEventListener( BaseClipEvent.CHANGED, sun_listener );
		show();
		initFields();
		clearFields();
		clearErrors();
		bar_changed( { value: Site.getApp().getSection() } );
	}
	
}